package com.jh.paymentchannel.service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLDecoder;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jh.paymentchannel.pojo.AutomaticRepaymentTask;
import com.jh.paymentchannel.pojo.AutomaticRepaymentTask2;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.jh.paymentchannel.business.AutomaticRepaymentTaskBusiness;
import com.jh.paymentchannel.helipay.service.HLRegisterService;
import com.jh.paymentchannel.helipay.service.QuickPayApi;
import com.jh.paymentchannel.util.Util;

import cn.jh.common.utils.CommonConstants;
import cn.jh.common.utils.UUIDGenerator;
import net.sf.json.JSONObject;


@Controller
public class AutomaticRepaymentTaskS {
    private static final Logger log = LoggerFactory.getLogger(AutomaticRepaymentTaskS.class);
    //private ScheduledExecutorService executorService=Executors.newScheduledThreadPool(10);
    @Autowired
    AutomaticRepaymentTaskBusiness automaticRepaymentTask;
    @Autowired
    Util util;
    @Autowired
    HLRegisterService hlr;
    @Autowired
    SpendService ss;
    @Autowired
    AutomaticRepaymentTaskService arts;
    @Autowired
    QuickPayApi qp;


    @RequestMapping(method = RequestMethod.POST, value = "/v1.0/paymentchannel/automaticrepaymenttask/add2")
    public @ResponseBody
    Object addAutomaticRepaymentTask2(HttpServletRequest request, final HttpServletResponse res,
                                      @RequestParam(value = "creditCardTasks", required = true) String creditCardTasks
    ) {
        Map<String, Object> map = new HashMap<>();
        res.setCharacterEncoding("UTF-8");
        res.setContentType("application/json;charset=UTF-8");
        List<AutomaticRepaymentTask2> creditCardTaskList;
        try {
            creditCardTaskList = JSON.parseArray(URLDecoder.decode(creditCardTasks, "utf-8"), AutomaticRepaymentTask2.class);
        } catch (Exception ex) {
            log.error(ex.getMessage());
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
            map.put(CommonConstants.RESP_MESSAGE, "客户端参数内容有误");
            return map;
        }
        if (null != creditCardTaskList && !creditCardTaskList.isEmpty()) {
            Date date = new Date();
            String batchNo = null;
            if (null != creditCardTaskList.get(0))
                batchNo = String.valueOf(creditCardTaskList.get(0).getUserId2()) + String.valueOf(date.getTime());
            for (int i = 0, size = creditCardTaskList.size(); i < size; i++) {

                AutomaticRepaymentTask model = new AutomaticRepaymentTask();
                AutomaticRepaymentTask2 creditCardTask;
                creditCardTask = creditCardTaskList.get(i);
                String order = UUIDGenerator.getUUID();
                model.setOrderCode(order);
                model.setUserId(creditCardTask.getUserId2());
                model.setBindId(creditCardTask.getBindId2());
                model.setType(creditCardTask.getType2());
                model.setStatus(creditCardTask.getStatus2());
                model.setBatchNo(batchNo);
                if (null != creditCardTask.getSingleFee2() && !"".equals(String.valueOf(creditCardTask.getSingleFee2())))
                    model.setSingleFee(creditCardTask.getSingleFee2());
                String payCard = creditCardTask.getPayCard2();
                if (payCard != null && !payCard.isEmpty())
                    model.setPayCard(payCard);
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                    model.setExecutionTime(sdf.parse(creditCardTask.getExecutionTime2()));
                    if (Float.valueOf(String.valueOf(creditCardTask.getRate2())) < Float.valueOf("0.0047")) {
                        map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                        map.put(CommonConstants.RESP_MESSAGE, "费率异常，请联系客服！");
                        return map;
                    }
                    model.setRate(creditCardTask.getRate2());
                    BigDecimal realAmount = creditCardTask.getRealAmount2();
                    if (realAmount != null) {
                        model.setRealAmount(realAmount);
                    }
                    model.setAmount(creditCardTask.getAmount2());
                } catch (Exception e) {
                    log.error(e.getMessage());
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                    map.put(CommonConstants.RESP_MESSAGE, "添加失败,参数转换异常");
                    return map;
                }
                model.setCreateTime(new Date());
                String amount = String.valueOf(creditCardTask.getAmount2());
                try {
                    model = automaticRepaymentTask.addAutomaticRepaymentTask(model);
                    int num = amount.indexOf(".");
                    double littlebalance = Double.parseDouble("0." + amount.substring(num + 1));//小数金额
                    String amountZ = amount.substring(0, num);//去掉小数金额
                    int surplus = Integer.valueOf(amountZ) % 2;//整除余数
                    int amountEll = Integer.valueOf(amountZ) - surplus;
                    int amountE = (int) ((double) amountEll / 2);
                    amountE = amountE + (int) (Math.random() * (amountE - 5));
                    int amountEEE = amountEll - amountE;
                    DecimalFormat decimalFormat = new DecimalFormat("0.00");
                    decimalFormat.setRoundingMode(RoundingMode.UP);
                    if (null != model && "1".equals(creditCardTask.getType2())) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        Date dayTime = sdf.parse(creditCardTask.getExecutionTime2());
                        long timss = dayTime.getTime();
                        Calendar calendar = Calendar.getInstance();
                    	/*if(i==0) {
                    		//HLRegisterService hlrs = new HLRegisterService();
                    		Object result = hlr.findSFAuthByPhone( "", creditCardTask.getBindId2(), "");
                    		log.info("=========================="+result+"===========================");
                    		RestTemplate restTemplate=new RestTemplate();
                    		URI uri = util.getServiceUrl("paymentchannel", "error url request!");
                    		String url = uri.toString() + "/v1.0/paymentchannel/hlregister/findbycard";
                    		MultiValueMap<String, String>  requestEntity  = new LinkedMultiValueMap<String, String>();
                			requestEntity.add("bindId", creditCardTask.getBindId2());
                			String result = restTemplate.postForObject(url, requestEntity, String.class);
                			log.info("接口/v1.0/paymentchannel/hlregister/findbycard--RESULT================"+result);
                			JSONObject jsonObject =  JSONObject.fromObject(result);
                			log.info("=========================="+jsonObject+"===========================");
                			String loginPhone = null;
                			if(jsonObject.containsKey("result")) {
                				JSONObject jobj = jsonObject.getJSONObject("result");
                				loginPhone = jobj.getString("loginPhone");
                			}else {
                				map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                				map.put(CommonConstants.RESP_MESSAGE, "未查询到登陆信息，请重试！");
                				return map;
                			}
                			根据userid查询用户贴牌
                			RestTemplate restTemplate=new RestTemplate();
                			URI uri = util.getServiceUrl("user", "error url request!");
                			String url = uri.toString() + "/v1.0/user/find/by/userid";
                			MultiValueMap<String, String>  requestEntity  = new LinkedMultiValueMap<String, String>();
                			requestEntity.add("userId", String.valueOf(creditCardTask.getUserId2()));
                			result = restTemplate.postForObject(url, requestEntity, String.class);
                			log.info("接口/v1.0/user/find/by/userid--RESULT================"+result);
                			jsonObject =  JSONObject.fromObject(result);
                			String brandId = null;
                			if(jsonObject.containsKey("result")) {
                				JSONObject jobj = jsonObject.getJSONObject("result");
                				brandId = jobj.getString("brandId");
                			}else {
                				map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                				map.put(CommonConstants.RESP_MESSAGE, "用户贴牌为空，请重试！");
                				return map;
                			}
                			
                			
                			final Map map2 = new HashMap();
                			map2.put(CommonConstants.RESP_CODE, "000000");
                			map2.put(CommonConstants.RESP_MESSAGE, "成功");
                			map2.put("result", "");
                			executorService.schedule(new Runnable() {
                				PrintWriter pw = res.getWriter();
                				public void run() {
                					JSONObject jsonobj = new JSONObject();
                					String obj = jsonobj.fromObject(map2).toString();
                					pw.write(obj);
                					pw.flush();
                					pw.close();
                					Calendar c = Calendar.getInstance();
                					log.info("==============结束"+c.getTimeInMillis()+"===============");
                				}
                			},4,TimeUnit.SECONDS );
                			
                			restTemplate=new RestTemplate();
                			uri = util.getServiceUrl("facade", "error url request!");
                			url = uri.toString() + "/v1.0/facade/topup";
                			log.info("=============="+url+"===============");
                			requestEntity  = new LinkedMultiValueMap<String, String>();
                			requestEntity.add("phone", loginPhone);
                			requestEntity.add("amount", amount);
                			requestEntity.add("channe_tag", "HL_PAY");
                			requestEntity.add("order_desc", "信用卡还款任务首笔余额验证");
                			requestEntity.add("brand_id", brandId);
                			requestEntity.add("bank_card", payCard);
                			log.info("接口/v1.0/facade/topup--参数================"+requestEntity);
                			result = restTemplate.postForObject(url, requestEntity, String.class);
                			log.info("接口/v1.0/facade/topup--RESULT================"+result);
                			JSONObject jobj = JSONObject.fromObject(result);
                			String orderson = jobj.getString("order");
                			if(CommonConstants.SUCCESS.equals(jobj.getString("resp_code"))) {
                				Boolean flag = true;
                				while(flag) {
                					result = ss.addSpend(request, "3", String.valueOf(creditCardTask.getAmount2()), payCard, batchNo, String.valueOf(creditCardTask.getUserId2()), creditCardTask.getBindId2(), "成功", sdf.format(new Date())+":00", order);
                					log.info("=========================="+result+"===========================");
                					restTemplate=new RestTemplate();
                					uri = util.getServiceUrl("paymentchannel", "error url request!");
                					url = uri.toString() + "/v1.0/paymentchannel/spend/add";
                					requestEntity  = new LinkedMultiValueMap<String, String>();
                					requestEntity.add("status", "3");
                					requestEntity.add("amount", String.valueOf(creditCardTask.getAmount2()));
                					requestEntity.add("executionTime", sdf.format(new Date())+":00");
                					requestEntity.add("payCard", payCard);
                					requestEntity.add("batchNo", batchNo);
                					requestEntity.add("bindId", creditCardTask.getBindId2());
                					requestEntity.add("userId", String.valueOf(creditCardTask.getUserId2()));
                					requestEntity.add("orderCode", order);
                					requestEntity.add("message", "成功");
                					result = restTemplate.postForObject(url, requestEntity, String.class);
                					jobj = JSONObject.fromObject(result);
                					if(!jobj.containsKey("result")||jobj.getJSONObject("result").isEmpty()) {
                					}else {
                						flag = false;
                					}
                				}
                			}else if("502".equals(jobj.getString("resp_message"))||jobj.getString("resp_message").contains("异常")){
                				QueryOrderVo qov = new QueryOrderVo();
                				qov.setP1_bizType("TransferQuery");
                				qov.setP2_orderId(orderson);
                				result = qp.queryOrder("TransferQuery", orderson, HeliPayBase.MERCHANT_NO, qov);
                				jsonObject = JSONObject.fromObject(result);
            					if ("订单查询成功".equals(jsonObject.getString("message"))) {
            						JSONObject jsonObj = jsonObject.getJSONObject("json");
            						if ("0000".equals(jsonObj.getString("rt2_retCode"))) {
            							if (jsonObj.containsKey("rt7_orderStatus")) {
            								
            								 * INIT已接收 DOING处理中 SUCCESS成功 FAIL失败 REFUND退款
            								 
            								if ("INIT".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
            										|| "DOING".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))
            										|| "SUCCESS".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
            									result = ss.addSpend(request, "3", String.valueOf(creditCardTask.getAmount2()), payCard, batchNo, String.valueOf(creditCardTask.getUserId2()), creditCardTask.getBindId2(), "成功", sdf.format(new Date())+":00", order);
            									log.info("=========================="+result+"===========================");
            								}
            							}
            						} else {
            							if (jsonObj.containsKey("rt7_orderStatus")) {
            								if ("REFUND".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
            									arts.deleteAutomaticRepaymentTaskByOrderCode(request, order);
            									map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
            	                				map.put(CommonConstants.RESP_MESSAGE, "交易异常，退款处理中！");
            	                				return map;
            								}
            								if ("FAIL".equalsIgnoreCase(jsonObj.getString("rt7_orderStatus"))) {
            									arts.deleteAutomaticRepaymentTaskByOrderCode(request, order);
            									map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
            	                				map.put(CommonConstants.RESP_MESSAGE, "首笔验证交易失败！");
            	                				return map;
            								}
            							}
            						}
            					}else {
            						arts.deleteAutomaticRepaymentTaskByOrderCode(request, order);
            						map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
	                				map.put(CommonConstants.RESP_MESSAGE, "首笔交易验证失败！");
	                				return map;
            					}
                			}else {
                				
                				arts.deleteAutomaticRepaymentTaskByOrderCode(request, order);
                				restTemplate=new RestTemplate();
                				uri = util.getServiceUrl("paymentchannel", "error url request!");
                				url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/delete/byordercode";
                				requestEntity  = new LinkedMultiValueMap<String, String>();
                				requestEntity.add("orderCode", order);
                				result = restTemplate.postForObject(url, requestEntity, String.class);
                				map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                				if(jobj.containsKey("resp_message")) {
                					map.put(CommonConstants.RESP_MESSAGE, jobj.getString("resp_message"));
                				}else {
                					map.put(CommonConstants.RESP_MESSAGE, "任务添加失败，付款卡内余额不足！");
                				}
                				return map;
                			}
                    	
                			
                    	}else {*/
                        for (int j = 0; j < 2; j++) {
                    			/*RestTemplate restTemplate=new RestTemplate();
                    			URI uri = util.getServiceUrl("paymentchannel", "error url request!");
                    			String url = uri.toString() + "/v1.0/paymentchannel/spend/add";
                    			MultiValueMap<String, String> requestEntity  = new LinkedMultiValueMap<String, String>();
                    			requestEntity.add("status", "0");*/
                            timss -= (1800000 + Math.random() * 1800000);
                            calendar.setTimeInMillis(timss);
                            dayTime = calendar.getTime();
                            Object result;
                            if (j == 0) {
                                result = ss.addSpend(request, "0", String.valueOf(amountE), payCard, batchNo, String.valueOf(creditCardTask.getUserId2()), creditCardTask.getBindId2(), "", "", sdf.format(dayTime) + ":00", order);
                                log.info("==========================" + result + "===========================");
                                //requestEntity.add("amount", String.valueOf(amountE));
                            } else {
                                result = ss.addSpend(request, "0", decimalFormat.format(new BigDecimal(String.valueOf(amountEEE)).add(new BigDecimal(littlebalance + surplus))), payCard, batchNo, String.valueOf(creditCardTask.getUserId2()), creditCardTask.getBindId2(), "", "", sdf.format(dayTime) + ":00", order);
                                log.info("==========================" + result + "===========================");
                                //requestEntity.add("amount", decimalFormat.format(new BigDecimal(String.valueOf(amountEEE)).add(new BigDecimal(littlebalance+surplus))));
                            }
                    			/*requestEntity.add("executionTime", sdf.format(dayTime)+":00");
                    			requestEntity.add("payCard", payCard);
                    			requestEntity.add("batchNo", batchNo);
                    			requestEntity.add("bindId", creditCardTask.getBindId2());
                    			requestEntity.add("userId", String.valueOf(creditCardTask.getUserId2()));
                    			requestEntity.add("orderCode", order);
                    			String result = restTemplate.postForObject(url, requestEntity, String.class);*/
                            JSONObject jobj = JSONObject.fromObject(result);
                            if (!jobj.containsKey("result") || jobj.getJSONObject("result").isEmpty()) {
                                result = arts.deleteAutomaticRepaymentTaskByOrderCode(order);
                                log.info("==========================" + result + "===========================");
                                result = arts.findAutomaticRepaymentTaskByOrderCode(order);
                                jobj = JSONObject.fromObject(result);
                                if (!jobj.containsKey("result") || jobj.getJSONObject("result").isEmpty()) {
                                    result = arts.deleteAutomaticRepaymentTaskByOrderCode(order);
                                    ss.deleteByOrderCode(order);
                                }
                    				/*restTemplate=new RestTemplate();
                    				uri = util.getServiceUrl("paymentchannel", "error url request!");
                    				url = uri.toString() + "/v1.0/paymentchannel/automaticrepaymenttask/delete/byordercode";
                    				requestEntity  = new LinkedMultiValueMap<String, String>();
                    				requestEntity.add("orderCode", order);
                    				result = restTemplate.postForObject(url, requestEntity, String.class);*/
                                map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                                map.put(CommonConstants.RESP_MESSAGE, "任务添加失败，请重试！");
                                return map;
                            }
                        }
                        Object result = arts.findAutomaticRepaymentTaskByOrderCode(order);
                        JSONObject jobj = JSONObject.fromObject(result);
                        log.info("==========================" + jobj + "===========================");
                        if (!jobj.containsKey("result") || jobj.getJSONObject("result").isEmpty()) {
                            arts.deleteAutomaticRepaymentTaskByOrderCode(order);
                            ss.deleteByOrderCode(order);
                        }
                        result = ss.querySpends(order);
                        jobj = JSONObject.fromObject(result);
                        log.info("==========================" + jobj + "===========================");
                        if (!jobj.containsKey("result")) {
                            arts.deleteAutomaticRepaymentTaskByOrderCode(order);
                            ss.deleteByOrderCode(order);
                        }
                        //}
                    }
                } catch (Exception e) {
                    log.error(e.toString());
                    map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
                    map.put(CommonConstants.RESP_MESSAGE, "添加失败,操作数据库异常");
                    return map;
                }
            }

        } else {
            map.put(CommonConstants.RESP_CODE, CommonConstants.ERROR_PARAM);
            map.put(CommonConstants.RESP_MESSAGE, "当前没有可执行的任务");
            return map;
        }

        map.put(CommonConstants.RESP_CODE, CommonConstants.SUCCESS);
        map.put(CommonConstants.RESP_MESSAGE, "添加成功");
        return map;
    }
}
